package com.mc.enjoy.module;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.mc.enjoy.NetworkUtils;
import com.mc.enjoy.R;
import com.mc.enjoy.ToastUtils;
import com.mc.enjoysdk.McTime;
import com.mc.enjoysdk.result.McResultBool;
import com.mc.enjoysdk.transform.McErrorCode;
import com.mc.enjoysdk.transform.McTimeFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;

/**
 * @author Woong on 1/27/21
 * @website http://woong.cn
 */
public class TimeActivity extends AppCompatActivity {
    private static final String TAG = "TimeActivity";

    private CheckBox cbAutoDateTime;
    private CheckBox cbAutoTimeZone;
    private CheckBox cbTimeFormat;
    private Button btnTime;
    private Button btnDate;
    private Spinner spinnerTimeZone;
    private Button btnNtp;
    private EditText etNtpAddress;
    private EditText etNtpTimeOut;
    private TimePickerDialog timePickerDialog;
    private TimePickerDialog.OnTimeSetListener timeSetListener;
    private DatePickerDialog datePickerDialog;
    private DatePickerDialog.OnDateSetListener dateSetListener;

    private McTime mcTime;
    private String[] timezones;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time);

        cbAutoDateTime = findViewById(R.id.cb_auto_date_time);
        cbAutoTimeZone = findViewById(R.id.cb_auto_timezone);
        cbTimeFormat = findViewById(R.id.cb_time_format);
        btnTime = findViewById(R.id.btn_time);
        btnDate = findViewById(R.id.btn_date);
        spinnerTimeZone = findViewById(R.id.spinner_timezone);
        btnNtp = findViewById(R.id.btn_ntp);
        etNtpAddress = findViewById(R.id.et_ndp_address);
        etNtpTimeOut = findViewById(R.id.et_ndp_timeout);

        initData();
        initListener();
    }

    private void initData() {
        mcTime = McTime.getInstance(this);
        cbAutoDateTime.setChecked(mcTime.isAutoDateAndTime() == McResultBool.TRUE);
        cbAutoTimeZone.setChecked(mcTime.isAutoTimeZone() == McResultBool.TRUE);
        cbTimeFormat.setChecked(mcTime.getCurrentTimeFormat() == McTimeFormat.HOUR_24);
        etNtpAddress.setText(mcTime.getNtpServerAddressInUse());
        etNtpTimeOut.setText(String.valueOf(mcTime.getNtpTimeout()));
        timezones = getResources().getStringArray(R.array.time_zone);
    }

    private void initListener() {
        cbAutoDateTime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int ret = mcTime.switchAutoDateAndTime(isChecked);
                parseError(ret);
            }
        });

        cbAutoTimeZone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int ret = mcTime.switchAutoTimeZone(isChecked);
                parseError(ret);
            }
        });

        cbTimeFormat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int ret = mcTime.setTimeFormat(isChecked ? McTimeFormat.HOUR_24 : McTimeFormat.HOUR_12);
                parseError(ret);
            }
        });

        timeSetListener = new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hour, int minute) {
                if (cbAutoDateTime.isChecked()) {
                    ToastUtils.showShort(TimeActivity.this, "已开启自动校时，无法手动配置时间");
                    return;
                }
                Log.i(TAG, "hour == " + hour + ", minute == " + minute +
                        ", second == " + 0 + ", millisecond == " + 0);
                int ret = mcTime.setTime(hour, minute, 0, 0);
                parseError(ret);
            }
        };

        dateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                if (cbAutoDateTime.isChecked()) {
                    ToastUtils.showShort(TimeActivity.this, "已开启自动校时，无法手动配置日期");
                    return;
                }
                Log.i(TAG, "year == " + year + ", month == " + month + ", day == " + day);
                int ret = mcTime.setDate(year, month, day);
                parseError(ret);
            }
        };

        btnTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                // 时间选择样式为圆盘
//                timePickerDialog = new TimePickerDialog(TimeActivity.this, timeSetListener,
//                        calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
                // 时间选择样式为滚轮
                timePickerDialog = new TimePickerDialog(TimeActivity.this, AlertDialog.THEME_HOLO_LIGHT, timeSetListener,
                        calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
                timePickerDialog.show();
            }
        });

        btnDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                // 日期选择样式为圆盘
//                datePickerDialog = new DatePickerDialog(TimeActivity.this, AlertDialog.THEME_HOLO_LIGHT, dateSetListener,
//                        calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
                // 日期选择样式为滚轮
                datePickerDialog = new DatePickerDialog(TimeActivity.this, AlertDialog.THEME_HOLO_LIGHT, dateSetListener,
                        calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
                datePickerDialog.show();
            }
        });

        spinnerTimeZone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                int ret = mcTime.setTimeZone(timezones[position]);
                parseError(ret);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        btnNtp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Executors.newCachedThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        if (!NetworkUtils.isAvailable(TimeActivity.this)) {
                            TimeActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.showShort(TimeActivity.this, "请检查网络是否连接");
                                }
                            });
                            return;
                        }

                        String address = etNtpAddress.getText().toString().trim();
                        if(address == null || "".equals(address)){
                            TimeActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.showShort(TimeActivity.this, "NTP 网址信息未填写");
                                }
                            });
                            return;
                        }
                        try{
                            Long.parseLong(etNtpTimeOut.getText().toString().trim());
                        }catch (Exception e){
                            TimeActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.showShort(TimeActivity.this, "NTP 延时信息不规范");
                                }
                            });
                            return;
                        }
                        long timeOut = Long.parseLong(etNtpTimeOut.getText().toString().trim());
                        if (mcTime.checkNtpServerAddressAvailable(address, timeOut) != McResultBool.TRUE) {
                            TimeActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.showShort(TimeActivity.this, "NTP 配置参数错误");
                                }
                            });
                            return;
                        }

                        final int ret = mcTime.setNtpServerAddress(address, timeOut);
                        TimeActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                parseError(ret);
                            }
                        });
                    }
                });
            }
        });
    }

    private void parseError(int errorCode) {
        switch (errorCode) {
            case McErrorCode.ENJOY_COMMON_SUCCESSFUL:
                ToastUtils.showShort(TimeActivity.this, "成功");
                break;
            case McErrorCode.ENJOY_COMMON_ERROR_SERVICE_NOT_START:
                ToastUtils.showShort(TimeActivity.this, "服务错误："+McErrorCode.errorCode2Str(errorCode));
                break;
            case McErrorCode.ENJOY_TIME_MANAGER_ERROR_PARAMETER_ERROR:
                ToastUtils.showShort(TimeActivity.this, "配置参数错误："+McErrorCode.errorCode2Str(errorCode));
                break;
            case McErrorCode.ENJOY_TIME_MANAGER_ERROR_FUNCTION_OCCUPY:
                ToastUtils.showShort(TimeActivity.this, "手动自动配置冲突："+McErrorCode.errorCode2Str(errorCode));
                break;
            case McErrorCode.ENJOY_COMMON_ERROR_UNKNOWN:
                ToastUtils.showShort(TimeActivity.this, "NTP 未知错误："+McErrorCode.errorCode2Str(errorCode));
                break;
            case McErrorCode.ENJOY_TIME_MANAGER_ERROR_NTP_SERVER_ADDRESS_SET_FAILED:
                ToastUtils.showShort(TimeActivity.this, "NTP 服务地址设置错误："+McErrorCode.errorCode2Str(errorCode));
                break;
            case McErrorCode.ENJOY_TIME_MANAGER_ERROR_NTP_TIMEOUT_SET_FAILED:
                ToastUtils.showShort(TimeActivity.this, "NTP 超时时间设置错误："+McErrorCode.errorCode2Str(errorCode));
                break;
            case McErrorCode.ENJOY_TIME_MANAGER_ERROR_NTP_CONFIG_SET_FAILED:
                ToastUtils.showShort(TimeActivity.this, "NTP 设置错误："+McErrorCode.errorCode2Str(errorCode));
                break;
            default:
                ToastUtils.showShort(TimeActivity.this, "未知错误："+McErrorCode.errorCode2Str(errorCode));
                break;
        }
    }
}
